/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.tom.social.fetcher.agent;

import jade.core.AID;
import jade.core.Agent;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import pl.tom.social.common.agent.behaviour.CancelBehaviour;
import pl.tom.social.fetcher.agent.behaviour.FetchNodeBehaviour;
import pl.tom.social.fetcher.jade.LocalJade;

/**
 *
 * @author Tom
 */
public class FetchNodeAgent extends Agent {

	private static final Logger logger = Logger.getLogger(FetchNodeAgent.class);
	private Thread download;
	private String url;

	public FetchNodeAgent(String url) {
		this.url = url;
	}

	@Override
	protected void setup() {
		String agentName = getAID().getName();

		// Printout a hello message
		logger.log(Level.INFO, "FetchNode-agent " + agentName + " starting");

		if (this.url == null) {
			Object[] args = getArguments();
			if (args != null && args.length > 0) {
				this.url = (String) args[0];
			} else {
				logger.log(Level.WARN, "Wrong arguments for FetchNode-agent " + agentName);
				return;
			}
		}

		AID receiver = LocalJade.getInstance().getTaskBarAgent(this);

		//Register behaviours
		this.addBehaviour(new FetchNodeBehaviour(url, receiver, download));
		this.addBehaviour(new CancelBehaviour());
	}

	@Override
	protected void takeDown() {
		// Printout a dismissal message
		logger.log(Level.INFO, "FetchNode-agent " + getAID().getName() + " terminating");
		
		try {
			if (download != null) {
				download.stop();
			}
		} catch (Exception ex) {
			logger.log(Level.ERROR, ex);
		}
	}
}
